
import { 
  createRouter, 
  createWebHistory,
  createWebHashHistory 
} from 'vue-router'
import type {RouteRecordRaw} from 'vue-router'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'

// 动态导入模块
const routerContext: Record<string,any> = import.meta.glob("./*.ts", { eager: true });

let routes:RouteRecordRaw[] = [
  {
    path:'/',
    name: 'home',
    meta: {
      auth: false,
      title: '主页',
      keepAlive: false
    },
    component: () => import('@/pages/home/Home.vue')
  },
  {
    path: '/user',
    name: 'user',
    meta: {
      auth: false,
      title: '我的',
      keepAlive: false
    },
    component: () => import('@/pages/user/User.vue')
  },
]
// console.log(routerContext);

Object.entries(routerContext).forEach(([k, v]: [string, ModuleType<RouteRecordRaw>]) =>{
  if(!['./index.ts'].includes(k)){
    routes.push(...v.default)
  }
})

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes,
  scrollBehavior(to, from, savedPosition) {
    // 在页面之间导航时控制滚动的函数
		if (savedPosition && to.meta.keepAlive) {
			return savedPosition // 浏览器上的前进后退按钮记录的位置对象
		} else {
      // 滚动到顶部
			return { top: 0 }
		}
	},
})

router.beforeEach(() => {
  // 开启
  NProgress.start()
})

router.afterEach(() => {
  // 关闭
  NProgress.done()
})

export default router
